#!/bin/bash -x

kata_coco_top_dir="$HOME/workspace/CoCo/"

kata_containers_repo_url="https://gitee.com/hanliyang-kata-coco/kata-containers.git"
kata_containers_repo_branch="3.13.0-hygon"
kata_containers_repo_dir="${kata_coco_top_dir}/kata-containers"

if [ ! -e ${kata_containers_repo_dir} ]; then
  git clone ${kata_containers_repo_url} \
    -b ${kata_containers_repo_branch} \
    ${kata_containers_repo_dir}
fi

# check and install yq if not exist
echo "Check and Install yq"
command yq > /dev/null
if [ $? -ne 0 ]; then
  DEBUG="y" ${kata_containers_repo_dir}/ci/install_yq.sh
  echo 'export PATH=$PATH:$HOME/go/bin/' >> $HOME/.profile
  source $HOME/.profile
fi

kernel_version="6.6.0-openeuler"
kernel_repo_url="https://gitee.com/openeuler/kernel.git"
kernel_repo_branch="OLK-6.6"
kernel_repo_commit="305d30148bc6eb27489370e9370f84eb88c3a467"
kernel_repo_dir="/dev/shm/openeuler-kernel"
kernel_builder_dir="${kata_containers_repo_dir}/tools/packaging/kernel"

LUKS_SECURE_MOUNT=0
if [ $LUKS_SECURE_MOUNT -eq 1 ]; then
  secure_mount="-m"
else
  secure_mount=""
fi

if [ ! -e ${kernel_repo_dir} ]; then
  git clone ${kernel_repo_url} \
    -b ${kernel_repo_branch} \
    ${kernel_repo_dir}
  pushd ${kernel_repo_dir}
  git reset --hard ${kernel_repo_commit}
  popd
fi

install_kata_guest_kernel_deps () {
  echo "Install kata guest kernel dependencies"
  sudo apt install -y \
    make gcc g++ \
    flex bison libssl-dev \
    libelf-dev
}

install_kata_guest_kernel_deps

build_install_guest_kernel () {
  echo "Build and Install kata guest kernel"

  pushd ${kernel_builder_dir}

  ./build-kernel.sh -a x86_64 \
    -d -x -f \
    ${secure_mount} \
    -k $kernel_repo_dir setup

  ./build-kernel.sh -a x86_64 \
    -d -x -f \
    ${secure_mount} \
    -k $kernel_repo_dir build

  #./build-kernel.sh -a x86_64 \
  #  -d -x -f \
  #  ${secure_mount} \
  #  -H deb \
  #  -k $kernel_repo_dir build-headers
  popd # ${kernel_builder_dir}

  kata_config_version=$(cat ${kernel_builder_dir}/kata_config_version)
  vmlinuz="vmlinuz-${kernel_version}-${kata_config_version}-csv"
  vmlinux="vmlinux-${kernel_version}-${kata_config_version}-csv"

  install_path=/opt/kata/share/kata-containers/
  sudo mkdir -p ${install_path} || true
  pushd ${kernel_repo_dir}
  sudo install --mode 0644 -D arch/x86/boot/bzImage $install_path/$vmlinuz
  sudo install --mode 0644 -D vmlinux $install_path/$vmlinux
  sudo install --mode 0644 -D ./.config \
    $install_path/config-${kernel_version}-${kata_config_version}-csv
  popd # ${kernel_repo_dir}
  pushd ${install_path}
  sudo ln -sf $vmlinuz vmlinuz-confidential-csv.container
  sudo ln -sf $vmlinux vmlinux-confidential-csv.container
  popd # ${install_path}
}

build_install_guest_kernel
